import auth from '../../utils/auth'
import VipService from '../../services/vip.js'
import UserService from '../../services/user.js'
import CdnService from '../../services/cdn.js'
// pages/i/index.js

Page({
    /**
     * 页面的初始数据
     */
    data: {
        isLoggedIn: false,
        userInfo: null,
        loginReady: false, // 登录是否准备完成
        vipStatus: {
            isVip: false,
            expireDate: ''
        },
        bizAdmin: false,
        companyMaster: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.checkLoginStatus()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 页面显示时检查登录状态
        if (this.data.loginReady) {
            this.checkLoginStatus();
        }
    },

    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
        try {
            const loginStatus = await auth.checkLoginStatus()
            this.setData({
                isLoggedIn: loginStatus.isLoggedIn,
                loginReady: true
            },function(){
                auth.refreshUserInfo().then(res => {
                    if(res.userInfo.phone){
                        res.userInfo.phone = '****' + res.userInfo.phone.slice(-4);
                    }
                    this.setData({
                        userInfo: res.userInfo
                    })
                })
            })

            // 如果已登录，加载VIP状态
            if (loginStatus.isLoggedIn) {
                this.loadVipStatus()
                this.loadBizAdmin()
                this.loadCompanyMaster()
            }
        } catch (error) {
            this.setData({
                isLoggedIn: false,
                userInfo: null,
                loginReady: true
            })
        }
    },

    /**
     * 加载VIP状态
     */
    async loadVipStatus() {
        try {
            const statusResult = await VipService.getStatus({ showLoading: false })
            if (statusResult.success) {
                const vipStatus = statusResult.data
                let expireDate = ''
                
                if (vipStatus.is_vip && vipStatus.vip_expire_time) {
                    const date = new Date(vipStatus.vip_expire_time * 1000)
                    expireDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
                }

                this.setData({
                    vipStatus: {
                        isVip: vipStatus.is_vip,
                        expireDate: expireDate
                    }
                })
            }
        } catch (error) {
            console.error('加载VIP状态失败:', error)
        }
    },

    async loadBizAdmin() {
        const bizAdminResult = await UserService.getBizAdmin({ showLoading: false })
        if (bizAdminResult.success) {
            this.setData({
                bizAdmin: bizAdminResult.data
            })
        }
    },

    async loadCompanyMaster() {
        const companyMasterResult = await UserService.isCompanyMaster({ showLoading: false })
        if (companyMasterResult.success) {
            this.setData({
                companyMaster: companyMasterResult.data
            })
        }
    },

    /**
     * 自动登录完成回调
     * 由app.js调用
     */
    onAutoLoginComplete(isLoggedIn, userInfo) {
        console.log('个人中心收到登录状态更新:', { isLoggedIn, userInfo });
        
        this.setData({
            isLoggedIn: isLoggedIn,
            loginReady: true
        },function(){
            auth.refreshUserInfo().then(res => {
                if(res.userInfo.phone){
                    res.userInfo.phone = '****' + res.userInfo.phone.slice(-4);
                }
                this.setData({
                    userInfo: res.userInfo
                })
            })
        });

        // 登录状态更新后重新加载VIP状态
        if (isLoggedIn) {
            this.loadVipStatus()
            this.loadBizAdmin()
            this.loadCompanyMaster()
        }
    },

    /**
     * 用户卡片点击事件
     */
    onUserCardTap() {
        const { isLoggedIn, userInfo } = this.data

        if (!isLoggedIn) {
            // 未登录，尝试自动登录
            this.autoLogin()
            return
        }

        if (!userInfo.phone || userInfo.phone.trim() === '') {
            // 已授权但手机号未绑定，跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
            return
        }

        // auth.refreshUserInfo().then(res => {
        //     this.setData({
        //         userInfo: res.userInfo
        //     })
        // })
    },

    

    /**
     * 自动登录
     */
    async autoLogin() {
        try {
            wx.showLoading({ title: '登录中...', mask: true })

            const loginResult = await auth.login()

            if (loginResult.success) {
                // 登录成功
                this.setData({
                    isLoggedIn: true,
                    userInfo: loginResult.userInfo
                })

                // 登录成功后加载VIP状态
                this.loadVipStatus()
                this.loadBizAdmin()
                this.loadCompanyMaster()

                this.setData({
                    isLoggedIn: true,
                    userInfo: loginResult.userInfo
                })

                wx.showToast({
                    title: '登录成功',
                    icon: 'success'
                })
            } else {
                // 登录失败
                wx.showModal({
                    title: '登录失败',
                    content: loginResult.message || '请重试',
                    showCancel: false
                })
            }
        } catch (error) {
            console.error('自动登录失败:', error)
            wx.showModal({
                title: '登录失败',
                content: '网络错误，请重试',
                showCancel: false
            })
        } finally {
            wx.hideLoading()
        }
    },

    toAddress() {
        const { isLoggedIn, userInfo } = this.data

        if (!isLoggedIn) {
            // 未登录，尝试自动登录
            this.autoLogin()
            return
        }

        if (!userInfo.phone || userInfo.phone.trim() === '') {
            // 已授权但手机号未绑定，跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
            return
        }
        
        wx.navigateTo({
            url: '/pages/i/address'
        })
    },

    toCard() {
        wx.navigateTo({
            url: '/pages/i/card'
        })
    },

    toBiz(e) {
        wx.navigateTo({
            url: '/pages/biz-manage/index'
        })
    },

    /**
     * 跳转到VIP页面
     */
    toVip() {
        const { isLoggedIn, userInfo } = this.data

        if (!isLoggedIn) {
            // 未登录，尝试自动登录
            this.autoLogin()
            return
        }

        if (!userInfo.phone || userInfo.phone.trim() === '') {
            // 已授权但手机号未绑定，跳转到登录页面
            wx.navigateTo({
                url: '/pages/index/login'
            })
            return
        }

        wx.switchTab({  
            url: '/pages/index/vip'
        })
        
    },

    toSetting() {
        wx.navigateTo({
            url: '/pages/i/setting'
        })
    },

    toCompany() {
        wx.navigateTo({
            url: '/pages/company/index'
        })
    },

    toScorePage() {
        wx.navigateTo({
            url: '/pages/i/score'
        })
    },

    toCardPage() {
        wx.navigateTo({
            url: '/pages/i/card'
        })
    },

    toOrderPage(e) {
        const { type, status } = e.currentTarget.dataset
        
        // 将type和status传递给order-boot页面
        const app = getApp();
        app.globalData.tabParam = {
            type: type,
            status: status
        };

        wx.switchTab({
            url: `/pages/i/order-boot`
        })
    },

    toScoreChargePage() {
        wx.navigateTo({
            url: '/pages/i/score-charge'
        })
    },

    updateAvatar() {
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    async bindChooseAvatar(e) {
        const { avatarUrl } = e.detail
        this.setData({
            userInfo: {
                ...this.data.userInfo,
                headimg_url: avatarUrl
            }
        },async function(){
            // 上传文件到
            const cdnResult = await CdnService.getAliyunCredit();
            if(cdnResult.success){
                wx.showLoading({
                    title: '上传图片中...'
                });
            }

            let data = cdnResult.data;

            let ext = avatarUrl.split('.').pop() || 'jpg';
            let path = CdnService.generateFilePath('avatar',ext);
            const ossFormData = {
                key: path,  //上传文件名称
                policy: data.policy,   //表单域
                'x-oss-signature-version': data.x_oss_signature_version,    //指定签名的版本和算法
                'x-oss-credential': data.x_oss_credential,   //指明派生密钥的参数集
                'x-oss-date': data.x_oss_date,   //请求的时间
                'x-oss-signature': data.signature,   //签名认证描述信息
                'x-oss-security-token': data.security_token,  //安全令牌
                success_action_status: "200"  //上传成功后响应状态码
            };

            let url = 'https://cloud--score-static.oss-cn-beijing.aliyuncs.com';
            wx.uploadFile({
                url, // 替换为实际的上传接口
                filePath: avatarUrl,
                name: 'file',
                formData: ossFormData,
                success: (res) => {
                    try {
                        if(res.statusCode == 200 && res.errMsg == 'uploadFile:ok'){

                            UserService.updateAvatar({
                                avatar: ossFormData.key,
                                showLoading: false
                            }).then(res => {
                                if(res.success){
                                    wx.hideLoading();
                                    wx.showToast({
                                        title: '上传成功',
                                        icon: 'success'
                                    });
                                }else{
                                    wx.hideLoading();
                                    wx.showToast({
                                        title: res.message,
                                        icon: 'none'
                                    });
                                }
                            })

                            
                        }else{
                            wx.hideLoading();
                            wx.showToast({
                                title: res.errMsg,
                                icon: 'none'
                            });
                        }
                    } catch (error) {
                        wx.hideLoading();
                        wx.showToast({
                            title: '上传失败',
                            icon: 'none'
                        });
                    }
                },
                fail: (error) => {
                    wx.hideLoading();
                    wx.showToast({
                        title: '上传失败',
                        icon: 'none'
                    });
                }
            });
        })
    },

    doScanOrderCode() {
        wx.scanCode({
            success: (result) => {
                let code = result.result;
                wx.navigateTo({
                    url: `/pages/i/set-order-express-no?id=${code}`
                });
            },
            fail: (error) => {
                wx.showToast({
                    title: '扫描失败',
                    icon: 'none'
                });
            }
        });
    }
})